﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Citi.Scheduler.Domain.Utils;
using System.Data.Objects;

namespace Citi.Scheduler.Domain
{
    public partial class RoutineError
    {
        public RoutineErrorHistory LastHistory
        {
            get {

                if (!RoutineErrorHistories.Any() || (RoutineErrorHistories.Any() && RoutineErrorHistories.Last().Date >= DateTime.Today.AddDays(-2)))
                {
                    try
                    {
                        Context.Instance.LoadProperty(this, y => y.RoutineErrorHistories, MergeOption.OverwriteChanges);
                    }
                    catch { }
                }

                return RoutineErrorHistories.Any() ? RoutineErrorHistories.Last() : new RoutineErrorHistory { Status = -1 }; 
            }
        }

        public IEnumerable<RoutineError> GetActiveErrors()
        {
            return SelectAllActive<RoutineError>().Where(x => x.LastHistory.Status == (short)RoutineErrorStatus.Opened);
        }

        public IEnumerable<RoutineError> GetErrorsByRoutineExecution(int routineExecutionId)
        {
            return SelectAllActive<RoutineError>().Where(x => x.RoutineExecutionId == routineExecutionId);
        }
    }
}
